//
//  ItemDetailViewController.m
//  Homepwner
//
//  Created by  on 12-4-22.
//  Copyright (c) 2012年 nju. All rights reserved.
//

#import "ItemDetailViewController.h"
#import "Possession.h"
#import "PossesionStore.h"

@implementation ItemDetailViewController
@synthesize nameField;
@synthesize serialNumberField;
@synthesize valueField;
@synthesize dateLabel;
@synthesize possession;
@synthesize imageView;
@synthesize imagePickerPopover;
@synthesize delegate;


- (void)dealloc {
    [nameField release];
    [serialNumberField release];
    [valueField release];
    [dateLabel release];
    [possession release]; 
    [imageView release];
    [super dealloc]; 
}

-(id) initForNewItem:(BOOL)isNew
{
    self = [super initWithNibName:@"ItemDetailViewController" bundle:nil];
    if(self)
    {
        if(isNew)
        {
            UIBarButtonItem *doneItem=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(save:)];
            [[self navigationItem] setRightBarButtonItem:doneItem];
            [doneItem release];
            UIBarButtonItem *cancelItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel:)];
            [[self navigationItem]setLeftBarButtonItem:cancelItem];
            [cancelItem release];
        }
    }
    return self;
}

-(IBAction)save:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
    if([delegate respondsToSelector:@selector(itemDetailViewControllerWillDismiss:)])
    {
        [delegate itemDetailViewControllerWillDismiss:self];
    }
}

-(IBAction)cancel:(id)sender
{
    [[PossesionStore defaultStore]removePossession:possession];
    [self dismissModalViewControllerAnimated:YES];
    if([delegate respondsToSelector:@selector(itemDetailViewControllerWillDismiss:)])
    {
        [delegate itemDetailViewControllerWillDismiss:self];
    }
}

-(id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    @throw [NSException exceptionWithName:@"Wrong initializer" reason:@"Use initForNewItem:" userInfo:nil];
    return nil;
}

- (void)viewDidUnload {
    [self setNameField:nil];
    [self setSerialNumberField:nil];
    [self setValueField:nil];
    [self setDateLabel:nil];
    [self setImageView:nil];
    [super viewDidUnload];
}

-(void) viewDidLoad
{   
    [super viewDidLoad];
    
    UIColor *clr=nil;
    if([[UIDevice currentDevice] userInterfaceIdiom]==UIUserInterfaceIdiomPad)
    {
        clr=[UIColor colorWithRed:0.875 green:0.88 blue:0.91 alpha:1];
    }
    else
    {
        clr=[UIColor groupTableViewBackgroundColor];
    }
    [[self view] setBackgroundColor:clr]; 
}

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [nameField setText:[possession possessionName]];
    [serialNumberField setText:[possession serialNumber]];
    [valueField setText:[NSString stringWithFormat:@"%d",[possession valueInDollars]]];
    
    NSDateFormatter  *dateFormatter=[[[NSDateFormatter alloc]init]autorelease];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    
    [dateLabel setText:[dateFormatter stringFromDate:[possession dateCreated]]];
    [[self navigationItem] setTitle:[possession possessionName]];
    
    NSString *imageKey=[possession imageKey];
    if(imageKey)
    {
        UIImage *imageToDisplay=[[ImageStore defaultImageStore] imageForKey:imageKey];
        [imageView setImage:imageToDisplay];
    }
    else
    {
        [imageView setImage:nil];
    }
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[self view]endEditing:YES];
    [possession setPossessionName:[nameField text]];
    [possession setSerialNumber:[serialNumberField text]];
    [possession setValueInDollars:[[valueField text]intValue]];
}

- (IBAction)takePicture:(id)sender 
{
    UIImagePickerController *imagePicker=[[UIImagePickerController alloc]init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
    }
    else
    {
        [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
    
    [imagePicker setDelegate:self];
    
    if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad)
    {
        self.imagePickerPopover = [[UIPopoverController alloc]initWithContentViewController:imagePicker];
        [self.imagePickerPopover setDelegate:self];
        [self.imagePickerPopover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
    else
    {
        [self presentModalViewController:imagePicker animated:YES];
    }
    
    [imagePicker release];
    
}

- (IBAction)backgroundTapped:(id)sender 
{
    [[self view] endEditing:YES];
}

- (IBAction)deleteImage:(id)sender 
{
    NSString *key=[possession imageKey];
    if(key)
    {
        [[ImageStore defaultImageStore] deleteImageForKey:key];
        [possession setImageKey:nil];
    }
    [[self imageView] setNeedsDisplay];
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *oldKey=[possession imageKey];
    if(oldKey)
    {
        [[ImageStore defaultImageStore] deleteImageForKey:oldKey];
    }
    
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    
    CFUUIDRef newUniqueID=CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef newUniqueIDString=CFUUIDCreateString(kCFAllocatorDefault, newUniqueID);
    [possession setImageKey:(NSString*)newUniqueIDString];
    CFRelease(newUniqueIDString);
    CFRelease(newUniqueID);
    
    [[ImageStore defaultImageStore]setImage:image forKey:[possession imageKey]];
    
    [imageView setImage:image];
    
    [possession setThumbnailDataFromImage:image];
    
    if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone)
    {
        [self dismissModalViewControllerAnimated:YES];
    }
    else
    {
        [imagePickerPopover dismissPopoverAnimated:YES];
        [imagePickerPopover autorelease];
        imagePickerPopover=nil;
    }
}

-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad)
    {
        return YES;
    }
    else
    {
        return (toInterfaceOrientation==UIInterfaceOrientationPortrait);
    }
}

@end
